package com.yc.alipayfront.controller;


import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.yc.alipayfront.config.AlipayConfig;
import com.yc.pay.api.resp.NetBankPayData;
import com.yc.pay.api.resp.RespVo;
import com.yc.pay.api.resp.TradeQueryRespData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/alipay")
public class AlipayController {


    private static final Logger logger = LoggerFactory.getLogger(AlipayController.class);

    @Autowired
    private AlipayConfig alipayConfig;

    @RequestMapping("/qrPay")
    public RespVo qrPay(){

        Factory.setOptions(this.getOptions());
        AlipayTradePrecreateResponse response = null;
        try {
            response = Factory.Payment.FaceToFace().preCreate("测试商品","202101021449","100");
        } catch (Exception e) {
            logger.error("Exception",e);
            return RespVo.returnFailRespVo(e.getMessage());
        }

        if (!"10000".equals(response.getCode())) {
            String msg = response.getMsg();
            return RespVo.returnFailRespVo(msg);
        }
        String qrCode =  response.getQrCode();
        NetBankPayData netBankPayData = new NetBankPayData() ;
        netBankPayData.setPayUrl(qrCode);
        return RespVo.returnSuccessRespVo(netBankPayData);



    }

    /**
     * 初始化支付宝系统参数
     * @return
     */
    private Config getOptions() {
        Config config = new Config();
        config.protocol = "https";
        config.gatewayHost = alipayConfig.getServiceUrl();
        config.signType = "RSA2";

        config.appId =  alipayConfig.getAppId(); //"<-- 请填写您的AppId，例如：2019091767145019 -->";

        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        config.merchantPrivateKey =  alipayConfig.getPivateKey();//"<-- 请填写您的应用私钥，例如：MIIEvQIBADANB ... ... -->";

        //注：证书文件路径支持设置为文件系统中的路径或CLASS_PATH中的路径，优先从文件系统中加载，加载失败后会继续尝试从CLASS_PATH中加载
//        config.merchantCertPath = "<-- 请填写您的应用公钥证书文件路径，例如：/foo/appCertPublicKey_2019051064521003.crt -->";
//        config.alipayCertPath = "<-- 请填写您的支付宝公钥证书文件路径，例如：/foo/alipayCertPublicKey_RSA2.crt -->";
//        config.alipayRootCertPath = "<-- 请填写您的支付宝根证书文件路径，例如：/foo/alipayRootCert.crt -->";

        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
        config.alipayPublicKey =  alipayConfig.getAlipayPubKey(); //"<-- 请填写您的支付宝公钥，例如：MIIBIjANBg... -->";

        //可设置异步通知接收服务地址（可选）
        config.notifyUrl =  alipayConfig.getNotifyUrl();//"<-- 请填写您的支付类接口异步通知接收服务地址，例如：https://www.test.com/callback -->";

        //可设置AES密钥，调用AES加解密相关接口时需要（可选）
//        config.encryptKey = "<-- 请填写您的AES密钥，例如：aa4BtZ4tspm2wnXLb1ThQA== -->";

        return config;
    }

    @RequestMapping("/query")
    public RespVo<TradeQueryRespData> alipayTradeQuery(@RequestParam("outTradeNo") String outTradeNo){
        //支付宝接口调用
        RespVo<TradeQueryRespData> respDataRespVo = new  RespVo<TradeQueryRespData>();

        if (StringUtils.isEmpty(outTradeNo)){

            return null;
        }


        try {

            Factory.setOptions(this.getOptions());
            AlipayTradeQueryResponse response = Factory.Payment.Common().query(outTradeNo);

            if (!"10000".equals(response.getCode())){
                return null;
            }

            respDataRespVo.setCode(0);
            respDataRespVo.setMsg("查询成功");

            TradeQueryRespData data = new  TradeQueryRespData();

            data.setPaySerialNo(response.getOutTradeNo());
            data.setStatus(response.getTradeStatus());

            respDataRespVo.setData(data);

            return respDataRespVo;

        } catch (Exception e) {
            logger.error("Exception",e);
            return null;

        }


    }

}
